package controllers

import (
	"cronjob/models"

	"strconv"
	"strings"
	"time"

	_ "github.com/astaxie/beego"
)

type RoleController struct {
	BaseController
}

//角色管理
func (this *RoleController) List() {
	this.Data["pageTitle"] = "角色管理"
	this.display()
}

// 加载数据
func (this *RoleController) Table() {
	//当前第几页
	page, err := this.GetInt("page")
	if err != nil {
		page = 1
	}

	//每页显示几个
	limit, err := this.GetInt("limit")
	if err != nil {
		limit = 5
	}

	this.pageSize = limit
	filters := make([]interface{}, 0)
	filters = append(filters, "status", 1)

	roleName := this.GetString("roleName")

	if roleName != "" {
		filters = append(filters, "role_name__icontains", roleName)
	}

	result, count := models.RoleGetList(page, limit, filters...)

	list := make([]map[string]interface{}, len(result))

	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["role_name"] = v.RoleName
		row["detail"] = v.Detail

		list[k] = row

	}

	this.ajaxList("角色加载", MSG_OK, count, list)
}

// 创建角色
func (this *RoleController) Add() {

	this.Data["zTree"] = true
	//服务组
	this.Data["serverGroup"] = serverLists(this.serverGroups, this.userID)

	//任务组
	this.Data["taskGroup"] = taskGroupLists(this.taskGroups, this.userID)

	this.Data["pageTitle"] = "新建角色"
	this.display()
}

// 保存角色
func (this *RoleController) AjaxSave() {
	role := new(models.Role)

	roleName := strings.TrimSpace(this.GetString("role_name"))

	// 修改不需要判断用户名
	role_id, _ := this.GetInt("id")
	if role_id == 0 {
		_, err := models.RoleByName(roleName)

		if err == nil {
			this.ajaxMsg("角色名称存在", MSG_ERR)
		}
	}

	role.RoleName = roleName

	role.Detail = strings.TrimSpace(this.GetString("detail"))
	role.ServerGroupIds = strings.TrimSpace(this.GetString("server_group_ids"))
	role.TaskGroupIds = strings.TrimSpace(this.GetString("task_group_ids"))

	auths := strings.TrimSpace(this.GetString("nodes_data"))

	role.UpdateTime = time.Now().Unix()
	role.UpdateId = this.userID
	role.Status = 1

	// 判断是否为0 新增还是修改
	if role_id == 0 {
		role.CreateTime = time.Now().Unix()
		role.CreateId = this.userID
		if id, err := models.RoleAdd(role); err != nil {
			this.ajaxMsg("", MSG_ERR)
		} else {
			authsArr := strings.Split(auths, ",")

			// res := make([]models.RoleAuth, 0)
			for _, v := range authsArr {

				ra := new(models.RoleAuth)
				ra.RoleId = id
				aid, _ := strconv.Atoi(v)
				if aid == 0 {
					continue
				}
				ra.AuthId = aid

				// res = append(res, ra)
				models.RoleAuthAdd(ra)
			}

			/**
			if len(res) > 0 {
				fmt.Println("ab")
				models.RoleAuthBatchAdd(&res)
			}
			*/
		}
		this.ajaxMsg("", MSG_OK)
	}

	role.Id = role_id

	if err := role.Update(); err != nil {
		this.ajaxMsg("修改失败", MSG_ERR)
	} else {
		// 删除该角色的权限
		models.RoleAuthDelete(role_id)

		authsArr := strings.Split(auths, ",")

		// res := make([]models.RoleAuth, 0)
		for _, v := range authsArr {

			ra := new(models.RoleAuth)

			aid, _ := strconv.Atoi(v)
			ra.RoleId = int64(role_id)

			if aid == 0 {
				continue
			}
			ra.AuthId = aid

			// res = append(res, ra)
			models.RoleAuthAdd(ra)
		}
		this.ajaxMsg("修改成功", MSG_OK)
	}

}

func (this *RoleController) Edit() {
	this.Data["zTree"] = true

	id, err := this.GetInt("id")

	role, err := models.RoleById(id)
	if err != nil {
		this.ajaxMsg("角色不存在", MSG_ERR)
	}
	// role.task_group_ids = role.TaskGroupIds
	// role.server_group_ids = role.ServerGroupIds

	row := make(map[string]interface{})
	row["id"] = role.Id
	row["role_name"] = role.RoleName
	row["detail"] = role.Detail
	row["task_group_ids"] = role.TaskGroupIds
	row["server_group_ids"] = role.ServerGroupIds

	this.Data["role"] = row

	//服务组
	this.Data["serverGroup"] = serverLists(this.serverGroups, this.userID)
	//任务组
	this.Data["taskGroup"] = taskGroupLists(this.taskGroups, this.userID)

	this.Data["pageTitle"] = "修改角色"

	// 控制权限
	roleAuths, err := models.RoleAuthById(id)
	auth := make([]int, 0)
	for _, v := range roleAuths {
		/// aid, _ := strconv.Atoi(v.AuthId)
		auth = append(auth, v.AuthId)
	}

	this.Data["auth"] = auth

	taskGroupIdsArr := strings.Split(role.TaskGroupIds, ",")
	taskGroupIds := make([]int, 0)
	for _, v := range taskGroupIdsArr {
		id, _ := strconv.Atoi(v)
		taskGroupIds = append(taskGroupIds, id)
	}

	serverGroupIdsArr := strings.Split(role.ServerGroupIds, ",")
	serverGroupIds := make([]int, 0)
	for _, v := range serverGroupIdsArr {
		id, _ := strconv.Atoi(v)
		serverGroupIds = append(serverGroupIds, id)
	}

	this.Data["server_group_ids"] = serverGroupIds
	this.Data["task_group_ids"] = taskGroupIds

	this.display()
}

// 角色删除
func (this *RoleController) AjaxDel() {
	// 获取删除角色的id
	id, _ := this.GetInt("id")

	// 根据角色查找
	role, err := models.RoleById(id)

	if err != nil {
		this.ajaxMsg("任务存在", MSG_ERR)
	}

	role.Status = 0

	if err := role.Update("status"); err != nil {
		this.ajaxMsg("删除失败", MSG_ERR)
	}

	this.ajaxMsg("删除成功", MSG_OK)
}
